package com.wang.tool.okhttp;

import okhttp3.Request;
import okhttp3.Response;

import java.io.IOException;

/**
 * @param <T>
 * @author shaopeng
 */
public interface HttpHandler<T> {

    /**
     * 填充req 默认只有url
     * 示例
     * json body
     * RequestBody reqbody = RequestBody.create(JSON.toJSONString(body), MediaType.parse("application/json; charset=utf-8"));
     * builder.post(reqbody);
     *
     * param body
     * FormBody.Builder formBodyBuilder = new FormBody.Builder();
     * formBodyBuilder.add(k,v);
     * builder.post(formBodyBuilder.build());
     *
     * 添加请求头
     * builder.addHeader("Authorization", "111");
     *
     * @param builder 非空
     * 抛出异常会转发到onError
     */
    void fillRequest(Request.Builder builder);

    /**
     * 读取
     * tips: 运行结束后,response会自动被回收
     * 获取流：
     *      try (InputStream inputStream = response.body().byteStream()) {
     *          // 处理数据流
     *      }
     * 读取短文本：
     *         InputStream inputStream = body.byteStream();
     *         ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
     *         byte[] buffer = new byte[4096];
     *         int bytesRead;
     *         while ((bytesRead = inputStream.read(buffer)) != -1) {
     *             outputStream.write(buffer, 0, bytesRead);
     *         }
     *
     *         String contentType = response.header("Content-Type");
     *         String charset = "UTF-8";
     *         if (contentType != null) {
     *             MediaType mediaType = MediaType.parse(contentType);
     *             if (mediaType != null) {
     *                 charset = String.valueOf(mediaType.charset(StandardCharsets.UTF_8));
     *             }
     *         }
     *         return outputStream.toString(charset);
     * @param response body非空 状态码正常
     * @return 结果
     * 抛出异常会转发到onError
     */
    T read(Response response) throws IOException;

    /**
     * 异常时
     *
     * @param error 非空
     * @return 此函数返回则future不会感知异常
     * @throws  Throwable 抛出异常会反映到结果的future中
     */
    T onError(Throwable error) throws Throwable;

}